/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gulangyu.trade.ws;


import com.mycompany.yourtrade.common.DerongVariables;
import com.qunshang.common.SessionUtils;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


public class LoginInterceptor extends HandlerInterceptorAdapter {   

 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws ServletException, IOException {

        HandlerMethod method = (HandlerMethod) handler;

        NeedLogin requestMapping = method.getMethodAnnotation(NeedLogin.class);
        NeedLogin controller = method.getMethod().getDeclaringClass().getAnnotation(NeedLogin.class);

        BeanFactory beans = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        DerongVariables systemVariables = beans.getBean(DerongVariables.class);

        if ((requestMapping != null || controller != null) && SessionUtils.getSession(request) == null) {
            response.sendRedirect(request.getContextPath().concat(systemVariables.getLoginUrl()));              
            return false;
        } else {
            return true; 
        }
    }
}